#include "reactor_server.hh"
#include "connection.hh"
#include "protocol.hh"
template<typename T>
bool servce_handler(connection_t *p_con,T servce)
{
    for (const auto &e : *p_con->get_packages())
    {
        auto req_pair = make_request(e);
        if (!req_pair.first)
            return false;
        request &req = req_pair.second;
        response res = servce(req);
        if (res._exit_code)
            return false;
        p_con->append_to_write_buffer(res.serialize() + '\n');
        // ET write directly
        p_con->write();
        if (p_con->is_write_buffer_empty())
            p_con->_p_back->modify_read_write(p_con->get_fd(), true, false);
        else
            p_con->_p_back->modify_read_write(p_con->get_fd(), true, true);
    }
}

response calculate(const request &req)
{
    int a = req._a;
    int b = req._b;
    char op = req._op;
    response ret;
    if (op == '+')
    {
        ret._exit_code = 0;
        ret._result = a + b;
    }
    else if (op == '-')
    {
        ret._exit_code = 0;
        ret._result = a - b;
    }
    else if (op == '*')
    {
        ret._exit_code = 0;
        ret._result = a * b;
    }
    else if (op == '/')
    {
        if (b == 0)
        {
            ret._exit_code = 1;
            ret._result = -1;
        }
        else
        {
            ret._exit_code = 0;
            ret._result = a / b;
        }
    }
    else if (op == '%')
    {
        if (b == 0)
        {
            ret._exit_code = 1;
            ret._result = -1;
        }
        else
        {
            ret._exit_code = 0;
            ret._result = a % b;
        }
    }
    return ret;
}
